var clickTarget = null;
layui.use([ 'jquery', 'form', 'layer' ], function() {
	let form = layui.form, $ = layui.jquery, layer = layui.layer;
	form.verify({
		// 唯一验证 input添加 data-checkurl:地址 data-checkhint:重复信息
		checkRemote : function(value, item) {
			let res = '';
			let hint = $(item).data("checkhint") || '';
			let url = $(item).data("checkurl");
			$.ajax({
				async : false,
				url : url,
				type : 'post',
				dataType : 'json',
				contentType : 'application/json',
				data : JSON.stringify({
					value : $.trim(value)
				}),
				success : function(data) {
					if (data.status == 'invalid') {
						res = hint;
					}
				},
				error : function() {
					res = '服务器error';
				}
			});
			if (res !== '') {
				return res;
			}
		}
	});

	
	$(".open-layer").on('click', function() {
		let $this = $(this);
		clickTarget = $this;
		let url = $this.data('url');
		let title = $this.data('title');
		openPage(title, url, iframeObjName)
	});

	

	$(".add-data-line").on("click", function(e) {
		e.preventDefault();
		let tpl = $(this).data('tpl');
		let $tpl;
		$.each($(".template"), function(i, item){
			let $item = $(item);
			if(tpl != undefined && $item.data('tpl') == tpl){
				$tpl = $item;
				return false;
			}
		});
		appendLine($(this).parents(".data-table"), $tpl, function($table, $clone) {
			let attr = $clone.find("input, textarea");
			$.each(attr, function(i, item){
				let $item = $(item);
				let verify = $item.data("verify");
				if (verify) {
					$item.attr('lay-verify', verify);
					$item.removeAttr('data-verify');
				}
			});
			
		});
		form.render();
	});

	$(".delete-row").on("click", function(e) {
		let $this = $(this);
		e.preventDefault();
		layer.confirm("确定删除吗？",  {icon: 3, title:'提示'}, function(index){
			deleteLine($this.data("url"), $this);
			layer.close(index);
		});
	});

	form.on("submit(submit-data-line)",function(){
		let map = new Map();
		let $template = $(".template");
		$.each($template, function(i, item){
			let tpl = $(item).data('tpl')
			$.each($(".data-line"), function(k, line){
				let $line = $(line);
				let lineTpl = $line.data('tpl')
				if(lineTpl == tpl){
					let obj = map.get(tpl);
					if(!obj){
						obj = [];
						map.set(tpl, obj);
					}
					obj.push(getDataFromLines($line));
				}
			});
		});
		if($template.length == 1){
			submitLines($("form").attr("action"), map.values().next().value);
		}else{
			submitLines($("form").attr("action"), map);
		}
		return false;
	});
	
	function appendLine($table, $template, func) {
		let $clone = $template.clone(true);
		$clone.removeClass("template").addClass("data-line");
		if (func) {
			func($table, $clone);
		}
		$table.append($clone);
		$clone.removeClass("hide");
	}

	function deleteLine(url, $this, func) {
		if ($.isEmptyObject(url)) {
			let p = $this.parentsUntil("tr").parent().remove();
			if (func) {
				func();
			}
		} else {
			$.get(url, {}, function(data) {
				if (data.status == "success") {
					location.reload();
					parent.layer.msg("删除成功");
				} else {
					layer.msg(data.message);
				}
			}, "json");
		}
	}

	function getDataFromLines($tr) {
		let res = {};
		$.each($tr.find("input, textarea"), function(i, item) {
			let $item = $(item);
			let key = $item.attr("name");
			if(!key){
				return true;
			}
			let value = '';
			switch (item.tagName.toLowerCase()) {
			case 'input':
				value = $item.val();
				break;
			case 'textarea':
				value = $item.val();
				break;
			}
			res[key] = value;
		});
		return res;
	}

	function submitLines(url, arr) {
		$.ajax({
			url : $("form").attr("action"),
			type : "post",
			dataType : "json",
			contentType: "application/json",
			data : arr instanceof Map ? JSON.stringify(mapToObj(arr)) : JSON.stringify(arr),
			success : function(data) {
				if (data.status == "success") {
					location.reload();
					parent.layer.msg("保存成功");

				}
			},
			fail : function() {
				parent.layer.msg("保存失败！");
			}
		})
	}

	function validateData(arr) {
		let result = true;
		$.each(arr, function(i, item) {
			if ($.trim(item.content) == '') {
				result = false;
				return false;
			}
		})
		return result;
	}
	
	
	/**
	 * 控制iframe窗口的刷新操作
	 */
	var iframeObjName;
	// 父级弹出页面
	function openPage(title, url, obj) {
		if (title == null || title == '') {
			title = false;
		}
		;
		if (url == null || url == '') {
			url = "404.html";
		}
		;
		iframeObjName = obj;
		// 如果手机端，全屏显示
		if (window.innerWidth <= 768) {
			var index = layer.open({
				type : 2,
				title : title,
				area : [ '320px', '350px' ],
				maxmin : true,
				fixed : false, // 不固定
				scrollbar: true,
				shadeClose: true,
				//closeBtn: 1,
				content : url,
				success: function(layero, index){
					layer.style(index, {
						  height: '350px',
					});       
				}
			});
			layer.full(index);
		} else {
			var index = layer.open({
				type : 2,
				title : title,
				area : ['1000px', '400px'],
				maxmin : true,
				fixed : false, // 不固定
				shadeClose: true,
				//closeBtn: 1,
				content : url,
				success: function(layero, index){
					layer.style(index, {
						  height: '400px',
					});       
				}
			});
		}
	}
	
	function mapToObj(map){
	    let obj= Object.create(null);
	    for (let[k,v] of map) {
	      obj[k] = v;
	    }
	    return obj;
	  }

});

